package org.cuit.echo.seon.unsafe;

import sun.misc.Unsafe;

import java.lang.reflect.Field;

/**
 * @author SeonExlike
 * @since 2024/3/25
 */
public class SunUnsafeFirstFace {
    public static void main(String[] args) throws NoSuchFieldException {
        School school = new School();
        school.setTime(2);


        Unsafe unsafe = getUnsafe();
        long offset = unsafe.objectFieldOffset(School.class.getDeclaredField("time"));
        System.out.println("offset = " + offset);

        unsafe.putInt(school, offset, 20);
        System.out.println("unsafe.getInt(school, offset) = " + unsafe.getInt(school, offset));

        System.out.println("school.getTime() = " + school.getTime());
    }

    public static Unsafe getUnsafe() {
        Unsafe unsafe;
        try {
            Field unsafeField = Unsafe.class.getDeclaredField("theUnsafe");
            unsafeField.setAccessible(true);
            unsafe = (Unsafe) unsafeField.get(null);
        } catch (NoSuchFieldException | IllegalAccessException e) {
            throw new RuntimeException(e);
        }
        return unsafe;
    }
}
